<template>
  <div class="login">
    <!-- X -->
    <div class="close">
      <i class="iconfont iconicon-test"></i>
    </div>
    <!-- logo -->
    <div class="logo">
      <i class="iconfont iconnew"></i>
    </div>
    <!-- 用户名 -->
    <div class="username">
      <hm-input  :rules="userRule" err-msg="请输入正确的账号(5-10位数字)" placeholder='请输入用户名' v-model="username"></hm-input>
    </div>
    <!-- 密码 -->
    <div class="password">
      <hm-input :rules="passRule" err-msg="请输入正确的密码(3-12位字符)'" placeholder='请输入密码' type='password' v-model='password'></hm-input>
    </div>
    <!-- 登录 -->
    <div class="login-btn">
      <hm-button @click='login'>登录</hm-button>
    </div>
    <!-- 跳转到注册页 -->
    <div class="go-register">
      没有账号? 立即 <router-link to="/register" class="register">注册</router-link>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      username: '',
      password: '',
      userRule: /^1\d{4,10}$/,
      passRule: /^\w{3,12}$/
    }
  },
  created () {
    // this.$router 整个的大的路由实例,一个应用就一个
    // this.$route 当前的路由的相关信息(路径, query参数, params参数)
    const { username, password } = this.$route.params
    if (username && password) {
      this.username = username
      this.password = password
    }
  },
  methods: {
    async login () {
      if (!this.userRule.test(this.username)) {
        this.$toast.success('请输入正确的用户名')
        return
      }
      if (!this.passRule.test(this.password)) {
        this.$toast.success('请输入正确的密码')
        return
      }
      const res = await this.$axios.post('/login', {
        username: this.username,
        password: this.password
      })
      // console.log(res)
      const { statusCode } = res.data
      if (statusCode === 200) {
        this.$toast.success('登录成功')

        // 将象征身份的令牌 token,存储到 locastorage中去
        const { token, user } = res.data.data
        localStorage.setItem('token', token)
        // user_id 页 要存储,将来获取个人信息要用
        localStorage.setItem('user_id', user.id)

        // 跳转到个人中心
        this.$router.push('/register')
      } else {
        this.$toast.fail('登录失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  padding: 20px;
  .close {
    i {
      font-size: 27px;
    }
  }
  .logo {
    text-align: center;
    i {
      font-size: 126px;
      color: #d81e06;
    }
  }
  .go-register {
    text-align: center;
    margin-top: 30px;
    .register {
      color: #d81e06;
    }
  }
}

</style>
